<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>订单数据调试工具</title>
    <style>
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
            max-width: 1200px;
            margin: 0 auto;
            padding: 20px;
            line-height: 1.6;
            background-color: #f5f5f5;
        }
        .container {
            background: white;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            padding: 24px;
            margin-bottom: 20px;
        }
        h1 {
            color: #333;
            margin-bottom: 24px;
        }
        h2 {
            color: #444;
            margin-top: 32px;
            margin-bottom: 16px;
            border-bottom: 2px solid #eaeaea;
            padding-bottom: 8px;
        }
        .tabs {
            display: flex;
            flex-wrap: wrap;
            margin-bottom: 20px;
            gap: 8px;
        }
        .tab-btn {
            padding: 10px 16px;
            border: 1px solid #ddd;
            background: #f8f8f8;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
            transition: all 0.3s;
        }
        .tab-btn.active {
            background: #4285f4;
            color: white;
            border-color: #4285f4;
        }
        .tab-content {
            display: none;
            padding: 20px;
            border: 1px solid #eaeaea;
            border-radius: 4px;
            background: #fafafa;
        }
        .tab-content.active {
            display: block;
        }
        .btn {
            padding: 10px 20px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
            margin-right: 10px;
            margin-bottom: 10px;
            transition: background-color 0.3s;
        }
        .btn-primary {
            background-color: #4285f4;
            color: white;
        }
        .btn-primary:hover {
            background-color: #3367d6;
        }
        .btn-secondary {
            background-color: #f8f8f8;
            color: #333;
            border: 1px solid #ddd;
        }
        .btn-secondary:hover {
            background-color: #e8e8e8;
        }
        pre {
            background: #f0f0f0;
            padding: 16px;
            border-radius: 4px;
            overflow-x: auto;
            white-space: pre-wrap;
            word-break: break-word;
            margin: 10px 0;
            font-family: 'Consolas', 'Monaco', 'Courier New', monospace;
            font-size: 13px;
        }
        .log {
            background: #f9f9f9;
            padding: 16px;
            border-radius: 4px;
            margin: 10px 0;
            border: 1px solid #eaeaea;
        }
        .log-entry {
            margin-bottom: 8px;
            font-size: 14px;
        }
        .log-entry.info {
            color: #333;
        }
        .log-entry.warn {
            color: #ff9800;
        }
        .log-entry.error {
            color: #f44336;
        }
        .log-entry.success {
            color: #4caf50;
        }
        .status-mapping {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
            gap: 10px;
            margin: 16px 0;
        }
        .status-item {
            padding: 12px;
            border: 1px solid #eaeaea;
            border-radius: 4px;
            background: white;
        }
        .order-list {
            display: flex;
            flex-direction: column;
            gap: 10px;
            margin: 16px 0;
        }
        .order-preview {
            padding: 12px;
            border: 1px solid #eaeaea;
            border-radius: 4px;
            background: white;
        }
        .order-preview-header {
            display: flex;
            justify-content: space-between;
            margin-bottom: 8px;
            font-weight: 500;
        }
        .order-preview-body {
            font-size: 14px;
            color: #666;
        }
        .success {
            color: #4caf50;
        }
        .warning {
            color: #ff9800;
        }
        .error {
            color: #f44336;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>订单数据调试工具</h1>
        <p>这个工具可以帮助您调试订单数据的加载和状态转换问题。点击下方按钮开始测试。</p>
        
        <button class="btn btn-primary" id="testBtn">测试订单数据加载和状态转换</button>
        <button class="btn btn-secondary" id="resetBtn">重置</button>
        
        <div class="tabs">
            <button class="tab-btn active" data-tab="log">执行日志</button>
            <button class="tab-btn" data-tab="api-response">API响应原始数据</button>
            <button class="tab-btn" data-tab="transformed-data">转换后订单数据</button>
            <button class="tab-btn" data-tab="status-mapping">状态映射详情</button>
            <button class="tab-btn" data-tab="orders-preview">订单预览</button>
        </div>
        
        <div class="tab-content active" id="log"></div>
        <div class="tab-content" id="api-response"></div>
        <div class="tab-content" id="transformed-data"></div>
        <div class="tab-content" id="status-mapping"></div>
        <div class="tab-content" id="orders-preview"></div>
    </div>

    <script>
        // 当前用户的token（从localStorage中获取）
        let userToken = localStorage.getItem('user_token') || '';
        
        // DOM元素
        const testBtn = document.getElementById('testBtn');
        const resetBtn = document.getElementById('resetBtn');
        const tabBtns = document.querySelectorAll('.tab-btn');
        const tabContents = document.querySelectorAll('.tab-content');
        const logContainer = document.getElementById('log');
        const apiResponseContainer = document.getElementById('api-response');
        const transformedDataContainer = document.getElementById('transformed-data');
        const statusMappingContainer = document.getElementById('status-mapping');
        const ordersPreviewContainer = document.getElementById('orders-preview');
        
        // 标签切换
        tabBtns.forEach(btn => {
            btn.addEventListener('click', () => {
                const tabId = btn.getAttribute('data-tab');
                
                // 移除所有active类
                tabBtns.forEach(b => b.classList.remove('active'));
                tabContents.forEach(c => c.classList.remove('active'));
                
                // 添加当前active类
                btn.classList.add('active');
                document.getElementById(tabId).classList.add('active');
            });
        });
        
        // 日志记录函数
        function log(message, type = 'info') {
            const logEntry = document.createElement('div');
            logEntry.className = `log-entry ${type}`;
            logEntry.textContent = `[${new Date().toLocaleTimeString()}] ${message}`;
            logContainer.appendChild(logEntry);
            logContainer.scrollTop = logContainer.scrollHeight;
            console.log(`[OrderDebug] ${message}`);
        }
        
        // 状态映射表 - 与Orders.vue中保持一致
        const statusMap = {
            'pending': '待付款',
            'paid': '待发货',
            'shipped': '待收货',
            'completed': '已完成',
            'cancelled': '已取消',
            'to_review': '待评价'
        };
        
        // 状态数字转字符串 - 与Orders.vue中保持一致
        function getStatusString(statusNumber) {
            const statusMap = {
                1: 'pending',    // 待付款
                2: 'paid',       // 已付款
                3: 'shipped',    // 待收货/已发货
                4: 'completed',  // 已完成
                5: 'cancelled',  // 已取消
                6: 'to_review',  // 待评价
                7: 'to_review'   // 待评价
            };
            return statusMap[statusNumber] || 'unknown';
        }
        
        // 格式化日期时间
        function formatDate(dateString) {
            if (!dateString) return '无';
            const date = new Date(dateString);
            if (isNaN(date.getTime())) return '无';
            
            const year = date.getFullYear();
            const month = String(date.getMonth() + 1).padStart(2, '0');
            const day = String(date.getDate()).padStart(2, '0');
            const hours = String(date.getHours()).padStart(2, '0');
            const minutes = String(date.getMinutes()).padStart(2, '0');
            
            return `${year}-${month}-${day} ${hours}:${minutes}`;
        }
        
        // 格式化订单商品数据
        function formatOrderItems(order) {
            if (!order) return [];
            
            // 模拟商品数据（因为实际API返回可能不包含详细items）
            const productCount = order.productCount || 0;
            const items = [];
            
            for (let i = 0; i < productCount; i++) {
                items.push({
                    id: `item_${order.orderNo}_${i}`,
                    productName: order.firstProductName || '商品名称',
                    price: (order.totalAmount / productCount) || 0,
                    quantity: 1,
                    productImage: `https://picsum.photos/id/${i + 10}/80/80`
                });
            }
            
            return items;
        }
        
        // 模拟API响应数据（如果无法访问实际API）
        const mockApiResponse = {
            "code": 200,
            "msg": "success",
            "data": {
                "total": 10,
                "list": [
                    {"orderNo":"2024091510000001","orderStatus":5,"orderStatusDesc":"待评价","totalAmount":8898,"createTime":"2024-09-15 10:25:00","productCount":8,"firstProductName":"Apple iPhone 15 Pro"},
                    {"orderNo":"2024091510000002","orderStatus":3,"orderStatusDesc":"待收货","totalAmount":239,"createTime":"2024-09-15 11:10:00","productCount":8,"firstProductName":"Apple iPhone 15 Pro"},
                    {"orderNo":"2024091510000003","orderStatus":6,"orderStatusDesc":"待评价","totalAmount":1259,"createTime":"2024-09-15 12:00:00","productCount":8,"firstProductName":"Apple iPhone 15 Pro"},
                    {"orderNo":"2024091510000004","orderStatus":7,"orderStatusDesc":"待评价","totalAmount":2099,"createTime":"2024-09-15 13:40:00","productCount":8,"firstProductName":"Apple iPhone 15 Pro"},
                    {"orderNo":"2025-09-15T15:55:29.040701500java.util.Random@7213f98e","orderStatus":1,"orderStatusDesc":"待付款","totalAmount":6098,"createTime":"2025-09-15 15:55:29","productCount":8,"firstProductName":"Apple iPhone 15 Pro"},
                    {"orderNo":"2025-09-15T16:04:22.120178400java.util.Random@773d94cc","orderStatus":1,"orderStatusDesc":"待付款","totalAmount":6098,"createTime":"2025-09-15 16:04:22","productCount":8,"firstProductName":"Apple iPhone 15 Pro"},
                    {"orderNo":"2424091510000001","orderStatus":6,"orderStatusDesc":"待评价","totalAmount":5000,"createTime":"2024-09-15 11:10:00","productCount":8,"firstProductName":"Apple iPhone 15 Pro"},
                    {"orderNo":"2025-10-09T11:05:23.867403500java.util.Random@2ae29bce","orderStatus":1,"orderStatusDesc":"待付款","totalAmount":299,"createTime":"2025-10-09 11:05:24","productCount":8,"firstProductName":"Apple iPhone 15 Pro"},
                    {"orderNo":"2025-10-09T11:06:15.632034100java.util.Random@7dfc0728","orderStatus":1,"orderStatusDesc":"待付款","totalAmount":5760.8,"createTime":"2025-10-09 11:06:16","productCount":8,"firstProductName":"Apple iPhone 15 Pro"},
                    {"orderNo":"2025-10-10T09:25:50.439490500java.util.Random@18e1817e","orderStatus":1,"orderStatusDesc":"待付款","totalAmount":899,"createTime":"2025-10-10 09:25:50","productCount":8,"firstProductName":"Apple iPhone 15 Pro"}
                ],
                "pageNum": 1,
                "pageSize": 10
            }
        };
        
        // 测试函数
        async function runTest() {
            log('开始测试订单数据加载和状态转换...', 'info');
            
            // 清空所有容器
            logContainer.innerHTML = '';
            apiResponseContainer.innerHTML = '';
            transformedDataContainer.innerHTML = '';
            statusMappingContainer.innerHTML = '';
            ordersPreviewContainer.innerHTML = '';
            
            try {
                // 1. 尝试获取实际API数据，如果失败则使用模拟数据
                let apiResponse;
                try {
                    log('尝试获取实际API数据...', 'info');
                    const response = await fetch('http://localhost:3000/api/orders', {
                        method: 'GET',
                        headers: {
                            'Content-Type': 'application/json',
                            'Authorization': `Bearer ${userToken}`
                        }
                    });
                    
                    if (!response.ok) {
                        throw new Error(`HTTP错误! 状态码: ${response.status}`);
                    }
                    
                    apiResponse = await response.json();
                    log('成功获取实际API数据', 'success');
                } catch (error) {
                    log(`无法获取实际API数据: ${error.message}，使用模拟数据进行测试`, 'warning');
                    apiResponse = mockApiResponse;
                }
                
                // 显示API响应原始数据
                apiResponseContainer.innerHTML = `<h3>API响应数据:</h3><pre>${JSON.stringify(apiResponse, null, 2)}</pre>`;
                
                // 2. 检查响应数据结构
                log('检查响应数据结构...', 'info');
                if (apiResponse.code === 200 && apiResponse.data && Array.isArray(apiResponse.data.list)) {
                    log(`数据结构有效，包含 ${apiResponse.data.list.length} 条订单记录`, 'success');
                } else {
                    log('响应数据结构不符合预期，无法进行后续测试', 'error');
                    apiResponseContainer.innerHTML += '<div class="error">响应数据结构不符合预期</div>';
                    return;
                }
                
                // 3. 转换订单数据（模拟Orders.vue中的转换逻辑）
                log('开始转换订单数据...', 'info');
                const orders = apiResponse.data.list.map((order, index) => {
                    // 生成订单ID
                    const orderId = `order_${index}_${Date.now()}`;
                    
                    // 转换状态
                    const orderStatus = order.orderStatus || order.status || 1;
                    const statusStr = getStatusString(orderStatus);
                    
                    const convertedOrder = {
                        id: orderId,
                        orderNo: order.orderNo || `NO_${orderId}`,
                        status: statusStr,
                        statusText: order.orderStatusDesc || statusMap[statusStr] || '未知状态',
                        totalAmount: order.totalAmount || order.amount || 0,
                        createTime: formatDate(order.createTime || order.createdAt),
                        items: formatOrderItems(order)
                    };
                    
                    log(`转换订单 #${index+1}: ${order.orderNo || '未知订单号'}，状态: ${orderStatus} -> ${statusStr} (${convertedOrder.statusText})`, 'info');
                    
                    return convertedOrder;
                });
                
                // 显示转换后的数据
                transformedDataContainer.innerHTML = `<h3>转换后订单数据:</h3><pre>${JSON.stringify(orders, null, 2)}</pre>`;
                
                // 4. 分析状态分布
                log('分析订单状态分布...', 'info');
                const statusStats = orders.reduce((acc, order) => {
                    acc[order.status] = (acc[order.status] || 0) + 1;
                    return acc;
                }, {});
                
                // 显示状态映射详情
                let statusMappingHtml = '<h3>状态映射详情:</h3>';
                statusMappingHtml += '<div class="status-mapping">';
                
                // 数字到字符串的映射
                statusMappingHtml += '<div><strong>数字 -> 字符串映射:</strong></div>';
                const numToStrMap = {
                    1: 'pending', 2: 'paid', 3: 'shipped', 4: 'completed', 5: 'cancelled', 6: 'to_review', 7: 'to_review'
                };
                for (let [num, str] of Object.entries(numToStrMap)) {
                    statusMappingHtml += `<div class="status-item">${num} -> ${str}</div>`;
                }
                
                // 字符串到中文的映射
                statusMappingHtml += '<div style="margin-top: 16px;"><strong>字符串 -> 中文映射:</strong></div>';
                for (let [str, zh] of Object.entries(statusMap)) {
                    statusMappingHtml += `<div class="status-item">${str} -> ${zh}</div>`;
                }
                
                // 状态分布统计
                statusMappingHtml += '<div style="margin-top: 16px;"><strong>订单状态分布:</strong></div>';
                for (let [status, count] of Object.entries(statusStats)) {
                    const zhStatus = statusMap[status] || status;
                    statusMappingHtml += `<div class="status-item">${zhStatus}: ${count} 个订单</div>`;
                }
                
                statusMappingHtml += '</div>';
                statusMappingContainer.innerHTML = statusMappingHtml;
                
                // 5. 显示订单预览
                log('生成订单预览...', 'info');
                let ordersPreviewHtml = `<h3>订单预览 (显示前5个):</h3>`;
                ordersPreviewHtml += '<div class="order-list">';
                
                orders.slice(0, 5).forEach(order => {
                    ordersPreviewHtml += `
                        <div class="order-preview">
                            <div class="order-preview-header">
                                <span>订单号: ${order.orderNo}</span>
                                <span class="${order.status === 'unknown' ? 'error' : 'success'}">${order.statusText}</span>
                            </div>
                            <div class="order-preview-body">
                                <div>创建时间: ${order.createTime}</div>
                                <div>总金额: ¥${Number(order.totalAmount).toFixed(2)}</div>
                                <div>商品数量: ${order.items.length} 件</div>
                            </div>
                        </div>
                    `;
                });
                
                ordersPreviewHtml += '</div>';
                ordersPreviewContainer.innerHTML = ordersPreviewHtml;
                
                // 6. 总结
                log(`测试完成！成功转换 ${orders.length} 条订单数据`, 'success');
                log(`订单状态分布: ${JSON.stringify(statusStats)}`, 'info');
                
                // 检查是否存在状态转换问题
                const hasUnknownStatus = orders.some(order => order.status === 'unknown');
                if (hasUnknownStatus) {
                    log('警告: 存在无法识别的订单状态，请检查getStatusString函数', 'warning');
                }
                
            } catch (error) {
                log(`测试过程中发生错误: ${error.message}`, 'error');
                console.error('测试错误:', error);
            }
        }
        
        // 重置函数
        function reset() {
            logContainer.innerHTML = '';
            apiResponseContainer.innerHTML = '';
            transformedDataContainer.innerHTML = '';
            statusMappingContainer.innerHTML = '';
            ordersPreviewContainer.innerHTML = '';
            log('已重置所有内容', 'info');
        }
        
        // 绑定事件
        testBtn.addEventListener('click', runTest);
        resetBtn.addEventListener('click', reset);
        
        // 初始化
        log('调试工具已加载完成，请点击测试按钮开始', 'info');
        log('注意：此工具会尝试调用实际API，如果失败则使用模拟数据', 'info');
    </script>
</body>
</html>